package org.trc.simulation.util;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFileChooser;

import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.FeatureCollections;
import org.geotools.feature.SchemaException;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.trc.network.Edge;

import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;

/**
 * 
 * @author Lin Xu
 *
 */

public class DataTransform { // 转换得到拓扑路网
	
	public static void RNTransform () throws IOException, SchemaException{
		File inputFile = JFileDataStoreChooser.showOpenFile("shp", null);
		
	    if (inputFile == null) {
	        return;
	    }
	    
	    //读取
		FileDataStore readDataStore = FileDataStoreFinder.getDataStore(inputFile);
		SimpleFeatureCollection featureCollection = readDataStore.getFeatureSource().getFeatures();
		SimpleFeatureIterator iterator = featureCollection.features();
		
		//输出  TODO:简化，原目录文件夹下输出即可
		JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");	
	    chooser.setDialogTitle("Save a new shapefile");
	    chooser.setSaveFile(inputFile);
        if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION) {
            return;
        }
        File outputShapefile = chooser.getSelectedFile();
     
		ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
		
		Map<String, Serializable> params = new HashMap<String, Serializable>();
		params.put("url", outputShapefile.toURI().toURL());
		params.put("create spatial index", Boolean.TRUE);
		
		ShapefileDataStore writeDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);

		// specify the feature type
		final SimpleFeatureType TYPE = DataUtilities.createType(
				"RoadSegment",
				"GEOM:MultiLineString:srid=4326," 
			    + "ID:String,"
			    + "SNODEID:String,"
			    + "ENODEID:String,"
			    + "DIRECTION:String,"
			    + "LENGTH:String"); //+ "DIRECTION:int,"

		writeDataStore.createSchema(TYPE);
		writeDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);

		//prepare new feature collection	
		SimpleFeatureCollection collection = FeatureCollections.newCollection();
		SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);

		SimpleFeature feature = null;
			
		while (iterator.hasNext()) {
			// create feature
			feature = iterator.next();
			featureBuilder.add(feature.getDefaultGeometry());
			featureBuilder.add(((Integer)feature.getAttribute("LinkID")).toString());
			featureBuilder.add(((Integer)feature.getAttribute("FROMNODENO")).toString());
			featureBuilder.add(((Integer)feature.getAttribute("TONODENO")).toString());
			featureBuilder.add("2");
			featureBuilder.add(((Double)feature.getAttribute("LENGTH")).toString());
			feature = featureBuilder.buildFeature(null);
			collection.add(feature);
		}

		//create transaction
		Transaction transaction = new DefaultTransaction("create");
		String typeName = writeDataStore.getTypeNames()[0];
		SimpleFeatureSource featureSource = writeDataStore.getFeatureSource(typeName);

		if (featureSource instanceof SimpleFeatureStore) {
			SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
			featureStore.setTransaction(transaction);
			try {
				featureStore.addFeatures(collection);
				transaction.commit();
			} catch (Exception problem) {
				problem.printStackTrace();
				transaction.rollback();
			} finally {
				transaction.close();
			}
			System.exit(0); // success!
		} else {
			System.out.println(typeName + " does not support read/write access");
			System.exit(1);
		}		
	}
	
	public static void main(String[] args) throws IOException, SchemaException {
		DataTransform.RNTransform();
	}
}
